﻿using Castle.MicroKernel.Facilities;
using GroceryList.Domain.Mapping;
using GroceryList.Domain.Model.Product;
using GroceryList.Front.Web.Helpers;
using NHibernate;
using Castle.MicroKernel.Registration;
using NHibernate.Cfg;

namespace GroceryList.Front.Web.Installers
{
    public class PersistenceFacility : AbstractFacility
    {
        protected override void Init()
        {
            var config = BuildDatabaseConfiguration();

            Kernel.Register(
                Component.For<ISessionFactory>()
                    .UsingFactoryMethod(config.BuildSessionFactory),
                Component.For<ISession>()
                    .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
                    .LifeStyle.Transient);
        }

        private Configuration BuildDatabaseConfiguration()
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Producto).Assembly);
            cfg.AddDeserializedMapping(NhMappingHelper.GetCompiledMappingFromAssembly(typeof(ListaCompraMap)), "Identifier");
            return cfg;
        }

    }
}